<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片转换工具 - 在线工具集合</title>
    <script src="../utils/toast.js"></script>
    <link rel="stylesheet" href="../utils/styles.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jsbarcode/3.11.5/JsBarcode.all.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pptxgenjs/3.12.0/pptxgen.min.js"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #0f0c29, #302b63, #24243e);
            min-height: 100vh;
            color: #fff;
            position: relative;
            overflow-x: hidden;
        }

        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: radial-gradient(circle at 50% 50%, rgba(255,255,255,0.1) 0%, transparent 50%);
            pointer-events: none;
            z-index: 0;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 40px 20px;
            position: relative;
            z-index: 2;
        }

        .header {
            text-align: center;
            margin-bottom: 40px;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            background: linear-gradient(45deg, #00ff88, #00b4d8);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .header p {
            color: rgba(255, 255, 255, 0.8);
            font-size: 1.1em;
        }

        .converter-section {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 24px;
            padding: 40px;
            margin-bottom: 30px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        }

        .upload-area {
            border: 2px dashed rgba(255, 255, 255, 0.2);
            border-radius: 20px;
            padding: 40px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-bottom: 30px;
            background: rgba(255, 255, 255, 0.03);
        }

        .upload-area:hover {
            border-color: #00ff88;
            background: rgba(255, 255, 255, 0.05);
        }

        .upload-area.dragover {
            border-color: #00ff88;
            background: rgba(0, 255, 136, 0.1);
        }

        .upload-icon {
            font-size: 48px;
            margin-bottom: 20px;
            color: #00ff88;
        }

        .upload-text {
            color: rgba(255, 255, 255, 0.8);
            font-size: 1.1em;
            margin-bottom: 10px;
        }

        .upload-hint {
            color: rgba(255, 255, 255, 0.5);
            font-size: 0.9em;
        }

        .conversion-options {
            background: rgba(255, 255, 255, 0.03);
            padding: 25px;
            border-radius: 20px;
            margin-bottom: 30px;
            border: 1px solid rgba(255, 255, 255, 0.05);
        }

        .option-group {
            margin-bottom: 20px;
        }

        .option-group:last-child {
            margin-bottom: 0;
        }

        .option-group label {
            display: block;
            margin-bottom: 10px;
            color: rgba(255, 255, 255, 0.9);
            font-size: 1em;
            font-weight: 500;
        }

        .format-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 15px;
        }

        .format-option {
            background: rgba(255, 255, 255, 0.05);
            padding: 15px;
            border-radius: 12px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .format-option:hover {
            background: rgba(255, 255, 255, 0.08);
            transform: translateY(-2px);
        }

        .format-option.active {
            background: rgba(0, 255, 136, 0.1);
            border-color: #00ff88;
        }

        .format-icon {
            font-size: 24px;
            margin-bottom: 8px;
            color: #00ff88;
        }

        .format-name {
            color: rgba(255, 255, 255, 0.8);
            font-size: 0.9em;
        }

        .preview-area {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .preview-box {
            background: rgba(255, 255, 255, 0.03);
            padding: 20px;
            border-radius: 16px;
            text-align: center;
            border: 1px solid rgba(255, 255, 255, 0.05);
        }

        .preview-box h3 {
            color: rgba(255, 255, 255, 0.9);
            margin-bottom: 15px;
            font-size: 1.1em;
        }

        .preview-image {
            max-width: 100%;
            max-height: 200px;
            border-radius: 8px;
            margin-bottom: 15px;
        }

        .image-info {
            color: rgba(255, 255, 255, 0.7);
            font-size: 0.9em;
            margin-bottom: 10px;
        }

        .action-buttons {
            display: flex;
            gap: 20px;
            justify-content: center;
            margin-top: 30px;
        }

        .action-btn {
            padding: 15px 30px;
            border: none;
            border-radius: 12px;
            background: linear-gradient(45deg, #00ff88, #00b4d8);
            color: #1a1a1a;
            font-size: 1.1em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0, 255, 136, 0.2);
            letter-spacing: 0.5px;
        }

        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0, 255, 136, 0.3);
        }

        .action-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .back-link {
            display: inline-block;
            margin-bottom: 20px;
            color: #00ff88;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .back-link:hover {
            transform: translateX(-5px);
        }

        @media (max-width: 768px) {
            .container {
                padding: 20px 10px;
            }

            .header h1 {
                font-size: 2em;
            }

            .action-buttons {
                flex-direction: column;
            }

            .action-btn {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <a href="../index.html" class="back-link">← 返回首页</a>
        
        <div class="header">
            <h1>图片转换工具</h1>
            <p>支持多种格式之间的转换，轻松处理图片文件</p>
        </div>

        <div class="converter-section">
            <div class="upload-area" id="uploadArea">
                <div class="upload-icon">📁</div>
                <div class="upload-text">点击或拖拽图片到这里</div>
                <div class="upload-hint">支持 JPG、PNG、WebP、GIF 等格式</div>
            </div>

            <div class="conversion-options">
                <div class="option-group">
                    <label>选择目标格式</label>
                    <div class="format-grid">
                        <div class="format-option" data-format="jpg">
                            <div class="format-icon">🖼️</div>
                            <div class="format-name">JPG</div>
                        </div>
                        <div class="format-option" data-format="png">
                            <div class="format-icon">🖼️</div>
                            <div class="format-name">PNG</div>
                        </div>
                        <div class="format-option" data-format="webp">
                            <div class="format-icon">🖼️</div>
                            <div class="format-name">WebP</div>
                        </div>
                        <div class="format-option" data-format="gif">
                            <div class="format-icon">🖼️</div>
                            <div class="format-name">GIF</div>
                        </div>
                        <div class="format-option" data-format="pdf">
                            <div class="format-icon">📄</div>
                            <div class="format-name">PDF</div>
                        </div>
                        <div class="format-option" data-format="word">
                            <div class="format-icon">📝</div>
                            <div class="format-name">Word</div>
                        </div>
                        <div class="format-option" data-format="excel">
                            <div class="format-icon">📊</div>
                            <div class="format-name">Excel</div>
                        </div>
                        <div class="format-option" data-format="powerpoint">
                            <div class="format-icon">📑</div>
                            <div class="format-name">PowerPoint</div>
                        </div>
                        <div class="format-option" data-format="base64">
                            <div class="format-icon">🔢</div>
                            <div class="format-name">Base64</div>
                        </div>
                        <div class="format-option" data-format="qrcode">
                            <div class="format-icon">📱</div>
                            <div class="format-name">二维码</div>
                        </div>
                        <div class="format-option" data-format="barcode">
                            <div class="format-icon">📦</div>
                            <div class="format-name">条形码</div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="preview-area" id="previewArea"></div>

            <div class="action-buttons">
                <button class="action-btn" id="convertBtn" disabled>开始转换</button>
                <button class="action-btn" id="downloadBtn" disabled>下载转换结果</button>
            </div>
        </div>
    </div>

    <script>
        const uploadArea = document.getElementById('uploadArea');
        const previewArea = document.getElementById('previewArea');
        const convertBtn = document.getElementById('convertBtn');
        const downloadBtn = document.getElementById('downloadBtn');
        const formatOptions = document.querySelectorAll('.format-option');

        let originalFile = null;
        let convertedFile = null;
        let selectedFormat = null;

        // 选择格式
        formatOptions.forEach(option => {
            option.addEventListener('click', () => {
                formatOptions.forEach(opt => opt.classList.remove('active'));
                option.classList.add('active');
                selectedFormat = option.dataset.format;
                
                if (originalFile) {
                    convertBtn.disabled = false;
                }
            });
        });

        // 拖拽上传
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            const file = e.dataTransfer.files[0];
            if (file && file.type.startsWith('image/')) {
                handleFile(file);
            } else {
                toast.error('请上传图片文件');
            }
        });

        // 点击上传
        uploadArea.addEventListener('click', () => {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = 'image/*';
            input.onchange = (e) => {
                const file = e.target.files[0];
                if (file) {
                    handleFile(file);
                }
            };
            input.click();
        });

        // 处理文件
        function handleFile(file) {
            originalFile = file;
            convertedFile = null;
            
            // 显示预览
            const reader = new FileReader();
            reader.onload = (e) => {
                previewArea.innerHTML = `
                    <div class="preview-box">
                        <h3>原始图片</h3>
                        <img src="${e.target.result}" class="preview-image">
                        <div class="image-info">大小: ${formatFileSize(file.size)}</div>
                        <div class="image-info">类型: ${file.type}</div>
                    </div>
                    <div class="preview-box">
                        <h3>转换预览</h3>
                        <div class="preview-image" style="display: flex; align-items: center; justify-content: center; background: rgba(255,255,255,0.05);">
                            等待转换...
                        </div>
                    </div>
                `;
                if (selectedFormat) {
                    convertBtn.disabled = false;
                }
                downloadBtn.disabled = true;
            };
            reader.readAsDataURL(file);
        }

        // 转换文件
        convertBtn.addEventListener('click', async () => {
            if (!selectedFormat) return;

            convertBtn.disabled = true;
            convertBtn.textContent = '转换中...';

            try {
                let result;
                switch (selectedFormat) {
                    case 'jpg':
                    case 'png':
                    case 'webp':
                    case 'gif':
                        if (!originalFile) {
                            throw new Error('请先上传图片');
                        }
                        result = await convertToImage(originalFile, selectedFormat);
                        break;
                    case 'pdf':
                        if (!originalFile) {
                            throw new Error('请先上传图片');
                        }
                        result = await convertToPDF(originalFile);
                        break;
                    case 'word':
                        if (!originalFile) {
                            throw new Error('请先上传图片');
                        }
                        result = await convertToWord(originalFile);
                        break;
                    case 'excel':
                        if (!originalFile) {
                            throw new Error('请先上传图片');
                        }
                        result = await convertToExcel(originalFile);
                        break;
                    case 'powerpoint':
                        if (!originalFile) {
                            throw new Error('请先上传图片');
                        }
                        result = await convertToPowerPoint(originalFile);
                        break;
                    case 'base64':
                        if (!originalFile) {
                            throw new Error('请先上传图片');
                        }
                        result = await convertToBase64(originalFile);
                        break;
                    case 'qrcode':
                        if (!originalFile) {
                            throw new Error('请先上传图片');
                        }
                        result = await convertToQRCode();
                        break;
                    case 'barcode':
                        if (!originalFile) {
                            throw new Error('请先上传图片');
                        }
                        result = await convertToBarcode();
                        break;
                }

                convertedFile = result;
                displayConversionResult();
                downloadBtn.disabled = false;
                toast.success('转换完成');
            } catch (error) {
                toast.error(error.message || '转换失败，请重试');
                console.error('转换错误:', error);
            } finally {
                convertBtn.disabled = false;
                convertBtn.textContent = '开始转换';
            }
        });

        // 下载转换结果
        downloadBtn.addEventListener('click', () => {
            if (!convertedFile) return;

            const link = document.createElement('a');
            link.href = URL.createObjectURL(convertedFile);
            link.download = `converted_${originalFile.name.split('.')[0]}.${selectedFormat}`;
            link.click();
            toast.success('开始下载');
        });

        // 转换函数
        async function convertToImage(file, format) {
            return new Promise((resolve, reject) => {
                const img = new Image();
                img.onload = () => {
                    const canvas = document.createElement('canvas');
                    canvas.width = img.width;
                    canvas.height = img.height;
                    const ctx = canvas.getContext('2d');
                    ctx.drawImage(img, 0, 0);
                    canvas.toBlob(blob => {
                        resolve(blob);
                    }, `image/${format}`);
                };
                img.onerror = reject;
                img.src = URL.createObjectURL(file);
            });
        }

        async function convertToPDF(file) {
            return new Promise((resolve, reject) => {
                const img = new Image();
                img.onload = () => {
                    const { jsPDF } = window.jspdf;
                    const doc = new jsPDF();
                    const canvas = document.createElement('canvas');
                    canvas.width = img.width;
                    canvas.height = img.height;
                    const ctx = canvas.getContext('2d');
                    ctx.drawImage(img, 0, 0);
                    const imgData = canvas.toDataURL('image/jpeg');
                    doc.addImage(imgData, 'JPEG', 10, 10, 190, 190);
                    const pdfBlob = doc.output('blob');
                    resolve(pdfBlob);
                };
                img.onerror = reject;
                img.src = URL.createObjectURL(file);
            });
        }

        async function convertToWord(file) {
            // 这里需要后端支持，因为浏览器端无法直接创建 Word 文件
            toast.error('Word 转换需要后端支持');
            throw new Error('Word conversion requires backend support');
        }

        async function convertToExcel(file) {
            return new Promise((resolve, reject) => {
                const img = new Image();
                img.onload = () => {
                    const canvas = document.createElement('canvas');
                    canvas.width = img.width;
                    canvas.height = img.height;
                    const ctx = canvas.getContext('2d');
                    ctx.drawImage(img, 0, 0);
                    const imgData = canvas.toDataURL('image/jpeg');
                    
                    const wb = XLSX.utils.book_new();
                    const ws = XLSX.utils.aoa_to_sheet([[imgData]]);
                    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
                    
                    const excelBlob = new Blob([XLSX.write(wb, { bookType: 'xlsx', type: 'array' })], 
                        { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                    resolve(excelBlob);
                };
                img.onerror = reject;
                img.src = URL.createObjectURL(file);
            });
        }

        async function convertToPowerPoint(file) {
            return new Promise((resolve, reject) => {
                const img = new Image();
                img.onload = () => {
                    const pptx = new PptxGenJS();
                    const slide = pptx.addSlide();
                    slide.addImage({ 
                        data: URL.createObjectURL(file),
                        x: 1,
                        y: 1,
                        w: '80%',
                        h: '80%'
                    });
                    pptx.writeBuffer().then(buffer => {
                        const pptxBlob = new Blob([buffer], 
                            { type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' });
                        resolve(pptxBlob);
                    });
                };
                img.onerror = reject;
                img.src = URL.createObjectURL(file);
            });
        }

        async function convertToBase64(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = () => {
                    const base64Blob = new Blob([reader.result], { type: 'text/plain' });
                    resolve(base64Blob);
                };
                reader.onerror = reject;
                reader.readAsDataURL(file);
            });
        }

        async function convertToQRCode() {
            return new Promise((resolve, reject) => {
                try {
                    // 将图片转换为 base64
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        const base64Data = e.target.result;
                        // 创建一个容器元素
                        const container = document.createElement('div');
                        container.style.display = 'none';
                        document.body.appendChild(container);
                        
                        // 创建二维码
                        const qrcode = new QRCode(container, {
                            text: base64Data,
                            width: 256,
                            height: 256,
                            colorDark: '#000000',
                            colorLight: '#ffffff',
                            correctLevel: QRCode.CorrectLevel.M
                        });
                        
                        // 等待二维码生成完成
                        setTimeout(() => {
                            const img = container.querySelector('img');
                            if (!img) {
                                document.body.removeChild(container);
                                reject(new Error('二维码生成失败'));
                                return;
                            }
                            
                            // 直接使用图片的 src
                            const imgUrl = img.src;
                            document.body.removeChild(container);
                            
                            // 将 base64 转换为 blob
                            fetch(imgUrl)
                                .then(res => res.blob())
                                .then(blob => resolve(blob))
                                .catch(error => reject(error));
                        }, 100);
                    };
                    reader.readAsDataURL(originalFile);
                } catch (error) {
                    reject(error);
                }
            });
        }

        async function convertToBarcode() {
            return new Promise((resolve, reject) => {
                try {
                    // 将图片转换为 base64
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        const base64Data = e.target.result;
                        const canvas = document.createElement('canvas');
                        JsBarcode(canvas, base64Data, {
                            format: "CODE128",
                            width: 2,
                            height: 100,
                            displayValue: true,
                            fontSize: 20,
                            margin: 10,
                            background: '#ffffff',
                            lineColor: '#000000'
                        });
                        canvas.toBlob(blob => resolve(blob), 'image/png');
                    };
                    reader.readAsDataURL(originalFile);
                } catch (error) {
                    reject(error);
                }
            });
        }

        // 显示转换结果
        function displayConversionResult() {
            if (selectedFormat === 'qrcode' || selectedFormat === 'barcode') {
                const reader = new FileReader();
                reader.onload = (e) => {
                    previewArea.innerHTML = `
                        <div class="preview-box">
                            <h3>转换预览</h3>
                            <img src="${e.target.result}" class="preview-image" style="background: white; padding: 20px; max-width: 300px; margin: 0 auto; display: block;">
                            <div class="image-info">类型: ${convertedFile.type}</div>
                        </div>
                    `;
                };
                reader.readAsDataURL(convertedFile);
            } else {
                const reader = new FileReader();
                reader.onload = (e) => {
                    const originalSize = originalFile.size;
                    const convertedSize = convertedFile.size;
                    const ratio = ((originalSize - convertedSize) / originalSize * 100).toFixed(1);

                    previewArea.innerHTML = `
                        <div class="preview-box">
                            <h3>原始图片</h3>
                            <img src="${URL.createObjectURL(originalFile)}" class="preview-image">
                            <div class="image-info">大小: ${formatFileSize(originalSize)}</div>
                            <div class="image-info">类型: ${originalFile.type}</div>
                        </div>
                        <div class="preview-box">
                            <h3>转换预览</h3>
                            <img src="${e.target.result}" class="preview-image">
                            <div class="image-info">大小: ${formatFileSize(convertedSize)}</div>
                            <div class="image-info">类型: ${convertedFile.type}</div>
                            <div class="compression-ratio">压缩率: ${ratio}%</div>
                        </div>
                    `;
                };
                reader.readAsDataURL(convertedFile);
            }
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
    </script>
</body>
</html> 